'use strict';
/**
 * Created by FreezeSoul on 2015/10/28.
 */
define([
    "app/core/base",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    "echarts"
], function (Chart, $, _, JSON, log, ec) {

    //TODO:自定义组件属性
    var property = {
        //标题文本
        TitleText: undefined,
        //标题颜色
        TitleColor: undefined,
        //副标题文本
        SubTitleText: undefined,
        //副标题颜色
        SubTitleColor: undefined,
        //背景色
        BackgroundColor: undefined,
        //序列颜色
        SeriesColors: undefined,
        //序列设置{SeriesIndex:0,LabelPosition:'',RadiusRange:"0%,80%"}
        SeriesOption: undefined,
        //标题位置
        TitlePosition: undefined,
        //序列字体颜色
        LegendTextColor: undefined,
        //图例位置
        LegendPosition: undefined,
        //是否显示工具栏
        IsShowToolbox: undefined,
        //需要针对组件映射属性至组件Option
        MapOption: function (option) {
            var _this = this;

            //标题
            if (this.TitleText) {
                $.extend(true, option, {title: {text: _this.TitleText}});
            }

            //标题颜色
            if (this.TitleColor) {
                $.extend(true, option, {title: {textStyle: {color: _this.TitleColor}}});
            }

            //副标题
            if (this.SubTitleText) {
                $.extend(true, option, {title: {subtext: _this.SubTitleText}});
            }

            //副标题颜色
            if (this.SubTitleColor) {
                $.extend(true, option, {title: {subtextStyle: {color: _this.SubTitleColor}}});
            }

            //背景色设置
            if (this.BackgroundColor) {
                option.backgroundColor = this.BackgroundColor;
            }

            //图例字体颜色
            if (this.LegendTextColor) {
                $.extend(true, option, {legend: {textStyle: {color: _this.LegendTextColor}}});
            }

            //标题位置设置
            if (this.TitlePosition) {
                $.extend(true, option, {
                    title: {
                        x: _this.TitlePosition.split(',')[0],
                        y: _this.TitlePosition.split(',')[1]
                    }
                });
            }

            //图例位置设置
            if (this.LegendPosition) {
                $.extend(true, option, {
                    legend: {
                        x: _this.LegendPosition.split(',')[0],
                        y: _this.LegendPosition.split(',')[1]
                    }
                });
            }

            //序列颜色
            if (this.SeriesColors
                && this.SeriesColors.length > 0) {
                option.color = this.SeriesColors;
            }

            //序列类型与堆积
            if (this.SeriesOption) {
                $.each(this.SeriesOption, function (i, seriesoption) {
                    var series = _.findWhere(option.series, {name: seriesoption.SeriesName});
                    if (series) {
                        series.type = "pie";

                        if (seriesoption.LabelPosition) {
                            $.extend(true, series, {
                                label: {
                                    normal: {
                                        position: seriesoption.LabelPosition
                                    }
                                }
                            });

                            if (seriesoption.LabelPosition == "outside") {
                                $.extend(true, series, {
                                    labelLine: {
                                        normal: {
                                            show: true
                                        }
                                    }
                                });
                            }
                        }

                        if (seriesoption.RadiusRange) {
                            var radiusArray = seriesoption.RadiusRange.split(',');
                            if (radiusArray.length >= 2) {
                                series.radius = $.parseJSON('["' + radiusArray[0] + '","' + radiusArray[1] + '"]');
                            }
                        }
                    }
                });
            }

            if (this.IsShowToolbox) {

                $.extend(true, option, {
                    toolbox: {
                        show: true,
                        feature: {
                            restore: {show: true},
                            saveAsImage: {show: true}
                        }
                    }
                });
            }
        }
    };

    var pie = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._chart = null;
            this._option = {
                Binding: [],
                Events: [],
                Extend: $.extend({}, property),
                Option: {
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b}: {c} ({d}%)"
                    },
                    legend: {
                        orient: 'vertical',
                        x: 'left',
                        data: ['直达', '营销广告', '搜索引擎', '邮件营销', '联盟广告', '视频广告', '百度', '谷歌', '必应', '其他']
                    },
                    toolbox: {
                        show: false
                    },
                    series: [
                        {
                            name: '访问来源',
                            type: 'pie',
                            selectedMode: 'single',
                            radius: [0, '30%'],
                            label: {
                                normal: {
                                    position: 'inner'
                                }
                            },
                            data: [
                                {value: 335, name: '直达', selected: true},
                                {value: 679, name: '营销广告'},
                                {value: 1548, name: '搜索引擎'}
                            ]
                        },
                        {
                            name: '访问来源',
                            type: 'pie',
                            radius: ['40%', '55%'],
                            data: [
                                {value: 335, name: '直达'},
                                {value: 310, name: '邮件营销'},
                                {value: 234, name: '联盟广告'},
                                {value: 135, name: '视频广告'},
                                {value: 1048, name: '百度'},
                                {value: 251, name: '谷歌'},
                                {value: 147, name: '必应'},
                                {value: 102, name: '其他'}
                            ]
                        }
                    ]
                }
            };
        },
        init: function (element) {
            try {
                this._chart = ec.init(element, null, {
                    renderer: 'canvas'
                });
                this._bindEvent();
            } catch (e) {
                log.error(e);
            }
        },
        //TODO:需要重写的部分
        _bindEvent: function () {
            var _this = this;
            this._chart.on("click", function (param) {
                if (_this._layout
                    && _this._layout.navigate
                    && _this._option.Events
                    && _this._option.Events.length > 0) {

                    var registerEvent = _.findWhere(_this._option.Events, {Event: "SeriesClick"});
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var dParam = _.findWhere(params, {Value: "Dimension"});
                        if (dParam && dParam.ParamName) {
                            args.push({
                                ParamName: dParam.ParamName,
                                ParamValue: param.name
                            });
                        }
                        var mParam = _.findWhere(params, {Value: "Measure"});
                        if (mParam && mParam.ParamName) {
                            args.push({
                                ParamName: mParam.ParamName,
                                ParamValue: param.value
                            });
                        }
                        var sParam = _.findWhere(params, {Value: "SeriesName"});
                        if (sParam && sParam.ParamName) {
                            args.push({
                                ParamName: sParam.ParamName,
                                ParamValue: param.seriesName
                            });
                        }

                        _this._layout.navigate(pageId, args);
                    }
                    param.event.event.preventDefault();
                }
            });
        },
        example: function () {
            try {
                this._chart.setOption(this._option.Option, true);
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                var propertyCopy = $.extend(true, {}, property);
                $.extend(true, propertyCopy, this._option.Extend);
                propertyCopy.MapOption(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        //TODO:需要重写的部分
        _bindData: function (data) {
            var tables = data;
            var _this = this;

            //清理工作
            this._option.Option.legend.data = [];

            //绑定数据
            $.each(this._option.Extend.SeriesOption, function (i, series) {
                if (series.DataSetCode && series.DimensionCode && series.MeasureCode) {
                    var table = tables[series.DataSetCode];

                    var binding = _.findWhere(_this._option.Binding, {DataSetCode: series.DataSetCode});
                    var dimension = _.findWhere(binding.Dimensions, {Code: series.DimensionCode}).Column;
                    var measure = _.findWhere(binding.Measures, {Code: series.MeasureCode}).Column;
                    var data = [];
                    $.each(table, function (j, row) {
                        if (_this._option.Option.legend.data.indexOf(row[dimension]) == -1) {
                            _this._option.Option.legend.data.push(row[dimension]);
                        }
                        data.push({
                            value: row[measure],
                            name: row[dimension]
                        });
                    });
                    if (_this._option.Option.series.length >= i + 1) {
                        _this._option.Option.series[i].type = 'pie';
                        _this._option.Option.series[i].name = series.SeriesName;
                        _this._option.Option.series[i].data = data;
                    } else {
                        _this._option.Option.series.push({
                            name: series.SeriesName,
                            type: 'pie',
                            selectedMode: 'single',
                            data: data
                        })
                    }
                }
            });
            //移除手工设置的
            if (this._option.Option.series.length > this._option.Extend.SeriesOption.length) {
                this._option.Option.series.splice(this._option.Extend.SeriesOption.length, this._option.Option.series.length - this._option.Extend.SeriesOption.length);
            }
        },
        setData: function (data) {
            try {
                this._readProperty();

                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                    && this._option.Extend.SeriesOption.length > 0
                    && _.every(this._option.Extend.SeriesOption, function (series) {
                        return series.DataSetCode && series.DimensionCode && series.MeasureCode;
                    })) {

                    this._bindData(data);

                    this._readProperty();
                }
                this._chart.setOption(this._option.Option, true);
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
                this._chart.setTheme(theme);
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
                this._chart.resize();
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                this._chart.dispose();
            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return null;
        },
        getChart: function () {
            return this._chart;
        }
    });

    return pie;
});
